package com.wwlwxg.util;

import lombok.extern.slf4j.Slf4j;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * @date 21-11-10 16:06
 */
@Slf4j
public class EmailUtil{
    private static final String HOST = "smtp.163.com";              //邮箱服务器地址
    private static final String PORT = "25";                        //发送邮件的端口
    private static final String AUTH = "true";                      //是否需要进行身份验证,视调用的邮箱而定，比方说QQ邮箱就需要，否则就会发送失败
    private static final String PROTOCOL = "smtp";                  //传输协议
    private static final String MAILFROM = "wwlwxg@163.com";   //发件人邮箱
    private static final String PERSONALNAME = "test";          //发件人邮箱别名
    private static final String USERNAME = "wwlwxg@163.com";   //发件人邮箱用户名
    private static final String PASSWORD = "DOTRDRZGDJOSGFIB";      //发件人邮箱密码
    private static final String MAILDEBUG = "false";                //是否开启debug
    private static final String CONTENTTYPE = "text/html;charset=UTF-8"; //邮件正文类型

    public static void sendMail(String subject,String  content,String toEmailAddress)  {
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", HOST);
            props.put("mail.smtp.auth", AUTH == null ? "true" : AUTH);
            props.put("mail.transport.protocol", PROTOCOL == null ? "smtp" : PROTOCOL);
            props.put("mail.smtp.port", PORT == null ? "25" : PORT);
            props.put("mail.debug", MAILDEBUG == null ? "false" : MAILDEBUG);
            //开启SSL
            props.setProperty("mail.smtp.socketFactory.port", "465");//设置ssl端口
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

            Session mailSession = Session.getInstance(props);

            // 设置session,和邮件服务器进行通讯。
            MimeMessage message = new MimeMessage(mailSession);
            // 设置邮件主题
            message.setSubject(subject);
            // 设置邮件正文
            message.setContent(content, CONTENTTYPE == null ? "text/html;charset=UTF-8" : CONTENTTYPE);
            // 设置邮件发送日期
            message.setSentDate(new Date());
            InternetAddress address = new InternetAddress(MAILFROM, PERSONALNAME);
            // 设置邮件发送者的地址
            message.setFrom(address);
            // 设置邮件接收方的地址
            message.setRecipients(Message.RecipientType.TO, toEmailAddress);
            Transport transport = mailSession.getTransport();
            message.saveChanges();

            transport.connect(HOST, USERNAME, PASSWORD);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }catch (Exception e){
            log.error("发送告警邮件失败：{}", e);
        }
    }

}
